package com.uzai.console.service.locallive.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.locallive.elmtoken.ElmTokenIdDto;
import com.uzai.console.dto.locallive.elmtoken.ElmTokenQuery;
import com.uzai.console.dto.locallive.elmtoken.ElmTokenUpdatePidDto;
import com.uzai.console.dto.tb.tbridpid.TbRidPidQuery;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.entity.TbRidPid;
import com.uzai.console.entity.TbToken;
import com.uzai.console.mapper.TbRidPidMapper;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.service.locallive.ElmTokenService;
import com.uzai.console.service.tb.tbridpid.TbRidPidService;
import com.uzai.console.vo.locallive.elmtoken.ElmTokenAuthUrlVo;
import com.uzai.console.vo.locallive.elmtoken.ElmTokenInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 饿了么配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class ElmTokenServiceImpl implements ElmTokenService {

    Logger logger = LoggerFactory.getLogger(ElmTokenServiceImpl.class);

    @Value("${tb.token.authorize}")
    private String authorizeUrl;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbRidPidMapper tbRidPidMapper;
    @Autowired
    private TbRidPidService tbRidPidService;

    /**
     * 查询饿了么联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenQuery
     * @return null
     */
    public Page<ElmTokenInfoVo> findElmTokenList(ElmTokenQuery elmTokenQuery){
        Integer now = DateUtil.getNowTime();
        //查询饿了么联盟
        elmTokenQuery.setType(1);
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        BeanUtils.copyProperties(elmTokenQuery, tbTokenQuery);

        //新建返回到页面的LIST对象
        List<ElmTokenInfoVo> elmTokenInfoVoList = new ArrayList<>();
        //执行分页查询对象
        Page<TbToken> page = new Page<>();
        tbTokenQuery.convert(page);
        ArrayList<TbToken> elmOrderList =  tbTokenMapper.findByList(page, tbTokenQuery);
        if(elmOrderList != null && elmOrderList.size() > 0){
            for (TbToken elmToken : elmOrderList){
                ElmTokenInfoVo elmTokenInfoVo = new ElmTokenInfoVo();
                BeanUtils.copyProperties(elmToken, elmTokenInfoVo);
                if(StringUtils.isNotBlank(elmToken.getPids())){
                    elmTokenInfoVo.setPidList(JSONObject.parseArray(elmToken.getPids(), String.class));
                }

                //到期时间
                Integer expiretime = Tools.getInteger(elmToken.getExptime());
                if(expiretime.intValue() <= now.intValue()){
                    elmTokenInfoVo.setExpireStatus(0);  //已到期
                }else if(expiretime.intValue() > now && expiretime.intValue() <= now + 7*24*3600){
                    elmTokenInfoVo.setExpireStatus(2);  //即将到期
                }else{
                    elmTokenInfoVo.setExpireStatus(1);  //未到期
                }


                elmTokenInfoVoList.add(elmTokenInfoVo);
            }
        }

        //返回到页面分页对象
        Page<ElmTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(elmTokenInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 添加授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public ElmTokenAuthUrlVo addElmToken(Long merId){
        //刷新授权的链接，将运营商ID放入自定义参数state当中，授权刷新之后，饿了么调用回调函数返回授权信息
        String merId_type =  "v3" + merId + "_1";
        String url =  authorizeUrl + merId_type;
        ElmTokenAuthUrlVo elmTokenAuthUrlVo = new  ElmTokenAuthUrlVo();
        elmTokenAuthUrlVo.setUrl(url);
        return elmTokenAuthUrlVo;
    }

    /**
     * 查询饿了么联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenIdDto
     * @return null
     */
    public ElmTokenInfoVo findElmTokenInfo(ElmTokenIdDto elmTokenIdDto){

        if(elmTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TbToken elmToken = tbTokenMapper.selectById(elmTokenIdDto.getId(), elmTokenIdDto.getMerId());
        if(elmToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该饿了么联盟账号不存在");
        }

        //返回页面对象
        ElmTokenInfoVo elmTokenInfoVo = new ElmTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(elmToken, elmTokenInfoVo);

        if(StringUtils.isNotBlank(elmToken.getElmPids())){
            elmTokenInfoVo.setPidList(JSONObject.parseArray(elmToken.getElmPids(), String.class));
        }

        //查询饿了么渠道id
        TbRidPidQuery tbRidPidQuery = new TbRidPidQuery();
        tbRidPidQuery.setMerId(elmTokenIdDto.getMerId());
        tbRidPidQuery.setTbTokenId(elmTokenIdDto.getId());
        List<TbRidPid> tbRidPidList = tbRidPidMapper.findByList(tbRidPidQuery);
        if(tbRidPidList != null && tbRidPidList.size() > 0){
            Set<String> relationIdSet = new HashSet<>(); //封装渠道id,去重复
            for(TbRidPid tbRidPid : tbRidPidList){
                relationIdSet.add(tbRidPid.getRelationId());
            }
            elmTokenInfoVo.setRelationIdSet(relationIdSet);
        }
        return elmTokenInfoVo;
    }

    /**
     * 修改联盟PID
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenUpdatePidDto
     * @return null
     */
    public void updatePid(ElmTokenUpdatePidDto elmTokenUpdatePidDto){

        if(elmTokenUpdatePidDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(elmTokenUpdatePidDto.getPidSet() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请设置推广位");
        }

        TbToken elmToken = tbTokenMapper.selectById(elmTokenUpdatePidDto.getId(), elmTokenUpdatePidDto.getMerId());
        if(elmToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该饿了么联盟账号不存在");
        }
        //授权饿了么pid
        elmToken.setElmPids(Tools.getStrEmpty(JSONObject.toJSONString(elmTokenUpdatePidDto.getPidSet())));

        tbTokenMapper.update(elmToken);

        //异步执行授权共享id
        //tbRidPidService.authRelationId(elmToken);

    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenIdDto
     * @return null
     */
    public void deleteElmToken(ElmTokenIdDto elmTokenIdDto){
        if(elmTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        TbToken tbToken = tbTokenMapper.selectById(elmTokenIdDto.getId(), elmTokenIdDto.getMerId());
        if(tbToken != null){
            if(tbToken.getType().intValue() == 2){ //淘宝和饿了么共享联盟
                tbToken.setType(0); //改成淘宝独享联盟
                tbTokenMapper.updateSelective(tbToken);
            }else{ //饿了么独享联盟，删除此联盟
                tbTokenMapper.deleteById(elmTokenIdDto.getId(), elmTokenIdDto.getMerId());
            }
        }
        //删除rid-pid关系
        tbRidPidMapper.deleteByTbTokenId(elmTokenIdDto.getId());
    }

    /**
     * 授权共享渠道id
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public ElmTokenAuthUrlVo authRelationId(Long merId){
        //添加普通会员授权用于pid
        String merId_type =  "v3" + merId + "_2";
        String url =  authorizeUrl + merId_type;
        ElmTokenAuthUrlVo elmTokenAuthUrlVo = new  ElmTokenAuthUrlVo();
        elmTokenAuthUrlVo.setUrl(url);
        return elmTokenAuthUrlVo;
    }

    /**
     * 清空共享渠道id
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenIdDto
     * @return null
     */
    public void cleanRelationId(ElmTokenIdDto elmTokenIdDto){

        if(elmTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        //清空共享渠道id
        tbRidPidMapper.deleteByTbTokenId(elmTokenIdDto.getId());
    }

    /**
     * 刷新共享渠道id
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param elmTokenIdDto
     * @return null
     */
    public void reflashRelationId(ElmTokenIdDto elmTokenIdDto){
        if(elmTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        TbToken tbToken_inviteCode = tbTokenMapper.selectById(elmTokenIdDto.getId(), elmTokenIdDto.getMerId());

        if(tbToken_inviteCode == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "饿了么授权不存在");
        }

        if(tbToken_inviteCode.getType().intValue() == 0){ //淘宝授权联盟
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不是饿了么授权");
        }

        //异步执行授权共享id
        tbRidPidService.authRelationId(tbToken_inviteCode);
    }

}
